package com.thread.threadfirst.SpringThreadPool;

import com.thread.threadfirst.ThreadFirstApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

/**
 * 异步方法
 */
@Component  //将此类在程序启动时动态注入进来
public class AsyncDemo {
    private static final Logger logger = LoggerFactory.getLogger(AsyncDemo.class);

    /**
     * 最简单的异步调用，返回值为void
     */
    @Async
    public void asyncInvokeSimplest() {
        logger.info("asyncInvokeSimplest");
    }

    /**
     * 带参数的异步调用 异步方法可以传入参数
     *
     * @param s
     */
    @Async
    public void asyncInvokeWithParameter(String s) {
        logger.info("asyncInvokeWithParameter,param={}", s);
    }

    /**
     * 异常调用返回Future 异步回调
     *
     * @param i
     * @return
     */
    //注意此处括号中的线程池名是自定义线程池的方法名(因为默认会以方法名来定义Bean的名字，当然也可以@Bean(name = "XXX")这样来自定义名字) 不是自定义线程池的线程名称前缀
    @Async("taskExecutor")
    public Future<String> asyncInvokeReturnFuture(int i) {
        logger.info("asyncInvokeReturnFuture,param={}", i);
        Future<String> future = null;
        try {
            Thread.sleep(1000 * 1);
            future = new AsyncResult<String>("success" + i);  //AsyncResult是Spring提供的一个Future接口的子类。isDone():可判断是否已经执行完毕。
        } catch (InterruptedException e) {
//            e.printStackTrace();
            future = new AsyncResult<String>("error");
        }
        return future;
    }

}
